//配置文件读取包
//读取XML
//读取INI文件
package config

import (
	cf "github.com/larspensjo/config"
	"log"
	"errors"
	"fmt"
)

func init() {

}
func ReadJdbcConfig(file, section string) (jdbcUrl string, maxOpen, maxIdle, maxLife int, err error) {
	cof, err := cf.ReadDefault(file)
	if err != nil {
		log.Println("读取数据库配置失败：", err.Error())
		return "", 0, 0, 0, errors.New(err.Error())
	}
	if cof.HasSection(section) {
		jdbcType, err := cof.String(section, "jdbc.type")
		if err != nil || len(jdbcType) == 0 {
			//默认使用MYSQL数据库
			jdbcType = "mysql"
		}
		jdbcHost, err := cof.String(section, "jdbc.host")
		if err != nil || len(jdbcHost) == 0 {
			//默认使用MYSQL数据库
			jdbcHost = "127.0.0.1"
		}
		jdbcPort, err := cof.String(section, "jdbc.port")
		if err != nil || len(jdbcPort) == 0 {
			jdbcPort = "3306"
		}
		jdbcUser, err := cof.String(section, "jdbc.user")
		if err != nil {
			jdbcUser = "root"
		}
		jdbcPass, err := cof.String(section, "jdbc.pass")
		if err != nil {
			jdbcPass = ""
		}

		jdbcCharset, err := cof.String(section, "jdbc.charset")
		if err != nil || len(jdbcCharset) == 0 {
			jdbcCharset = "utf8"
		}
		jdbcSechma, err := cof.String(section, "jdbc.schema")
		if err != nil || len(jdbcSechma) == 0 {
			jdbcSechma = "mysql"
		}

		jdbcMaxOpen, err := cof.Int(section, "jdbc.maxOpen")
		if err != nil || jdbcMaxOpen == 0 {
			jdbcMaxOpen = 200
		}
		jdbcMaxIdle, err := cof.Int(section, "jdbc.maxIdle")
		if err != nil || jdbcMaxIdle == 0 {
			jdbcMaxIdle = 100
		}
		jdbcMaxLifeTime, err := cof.Int(section, "jdbc.maxLifeTime")
		if err != nil || jdbcMaxLifeTime == 0 {
			jdbcMaxLifeTime = -1
		}

		if len(jdbcUser) == 0 {
			return "", 0, 0, 0, errors.New("数据库用户名不能为空！")
		}
		return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", jdbcUser, jdbcPass, jdbcHost, jdbcPort, jdbcSechma, jdbcCharset), jdbcMaxOpen, jdbcMaxIdle, jdbcMaxLifeTime, nil
	}
	return "", 0, 0, 0, errors.New("无法读取对应模式下的数据库配置信息！")
}


